import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 徐海涛
 * Date: 2022-02-23
 * Time: 13:36
 */
public class HashBuck {//哈希桶
    //构造节点
    static class Node {
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;//桶的底层是数组
    public int usedSize;
    public static final double DEFAULT_LOAD_FACTOR = 0.75;//载荷因子
    public HashBuck() {
        this.array = new Node[10];
    }

    /**
     * put 函数
     * @param key
     * @param val
     */
    public void put(int key,int val) {
        //1.找到key所在的位置
        int index = key % this.array.length;

        //2.遍历这个下标的链表，看是不是有相同的key，有要更新value值得
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                cur.val = val;//更新val值
                return;
            }
            cur = cur.next;
        }
        //3.没有这个key 这个元素
        //头插或者尾插,这里头插
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //4.插入元素成功之后，检查当前散列表的负载因子
        if(loadFactor()>= DEFAULT_LOAD_FACTOR) {//超过了0.75要扩容
            resize();//
        }
    }


    public void resize() {
        Node[] newArray = new Node[array.length*2];
        for (int i = 0; i < this.array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                int index = cur.key % newArray.length; //获取新的下标
                //就是把cur这个节点以头插或者尾插 插入到新的数组对应下标的链表当中
                Node curNext = cur.next;//画图好理解
                cur.next = newArray[i];//先绑定后面
                newArray[i] = cur;//绑定前面
                cur = curNext;
            }
        }
        array = newArray;
    }

    private double loadFactor() {
        return 1.0*this.usedSize/array.length;
    }

    /**
     * 根据key获取val值
     * @param key
     * @return
     */
    public int get(int key) {
        //1.找到key所在的位置
        int index = key % this.array.length;
        //2.遍历这个下标的链表，看是不是有相同的key,有要更新val
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

    public static void main(String[] args) {
        HashBuck hashBuck = new HashBuck();
        hashBuck.put(1,1);
        hashBuck.put(12,12);
        hashBuck.put(3,3);
        hashBuck.put(6,6);
        hashBuck.put(7,7);
        hashBuck.put(2,2);
        hashBuck.put(11,11);
        hashBuck.put(8,8);
        System.out.println(hashBuck.get(11));
    }
}
